package com.jy.oms.framework.thread;

import com.jy.oms.framework.closed.ClosedEventListenerHandler;
import com.jy.oms.framework.util.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 线程优雅停机；
 * k8s容器销毁如果无法触发钩子(Runtime.addShutdownHook)，则在k8s停止前调用此链接
 * 如：
 * lifecycle:
 *  preStop:
 *   exec:
 *    command: ["curl", "-XPOST", "127.0.0.1:8080/thread/shutdown"]
 *
 * @author liuquan
 */
@WebServlet("/thread/shutdown")
public class ThreadGracefulStopServlet extends HttpServlet {
    private static Logger logger = LoggerFactory.getLogger(ThreadGracefulStopServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.warn("异步任务开始停止.................");

        CloseableThreadManager threadManager = SpringUtil.getBean(CloseableThreadManager.class);
        threadManager.gracefulStop();

        ClosedEventListenerHandler closedEventListenerHandler = SpringUtil.getBean(ClosedEventListenerHandler.class);
        closedEventListenerHandler.gracefulStop();
    }

}
